package com.dgshanger.sanhxiaofeisc.ui.home.utils;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;

import com.blankj.utilcode.util.ImageUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.dgshanger.sanhxiaofeisc.R;
import com.dgshanger.sanhxiaofeisc.common.Constants;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;


/**
 * @创建者 mingyan.su
 * @创建时间 2017/8/16 14:09
 * @类描述 ${TODO}基于glide的图片加载工具类
 */
public class ImageLoader {
    //
    private static final int DEFAULT_IMAGE = R.drawable.print_load_;
    private static final int ERROR_IMAGE = R.drawable.print_load_;


    /**
     * 获取完整的Url
     *
     * @param url 不一定完整的Url
     * @return
     */
    public static String getUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return "";
        }
        if (!url.contains("http")) {
            return Constants.getBaseUrl() + url;
        }
        return url;
    }


    public static void loadToUrl(Context context, final ImageView imageView, String url) {
        Glide.with(context).
                load(getUrl(url))//图片的url
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片
//                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(imageView);
    }

    public static void loadToUrl2(Context context, final ImageView imageView, String url) {
        Glide.with(context).
                load(url)//图片的url
                .asBitmap()
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片
                //                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    public static void loadToUrl(Context context, ImageView imageView, String url, RequestListener listener) {
        Glide.with(context).
                load(url)//图片的url
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片

//                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .listener(listener)
                .into(imageView);//加载
    }

    public static void setImageViewHead(Context context, final ImageView imageView, String url) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(DEFAULT_IMAGE)
                .centerCrop()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(resource);
                    }
                });
    }

    public static void loadToUrlRound(Context context, final ImageView imageView, String url) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .placeholder(DEFAULT_IMAGE)
                .centerCrop()
                .error(ERROR_IMAGE) //加载失败的图片
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(ImageUtils.toRound(resource));
                    }
                });
    }

    public static void loadToResRound(Context context, final ImageView imageView, int imageResId) {
        Glide.with(context)
                .load(imageResId)
                .asBitmap()
                .placeholder(DEFAULT_IMAGE)
                .centerCrop()
                .error(ERROR_IMAGE) //加载失败的图片
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(ImageUtils.toRound(resource));
                    }
                });
    }


    public static void loadAvatar(Context context, ImageView imageView, String url) {
        Glide.with(context).
                load(getUrl(url))//图片的url
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(DEFAULT_IMAGE) //加载失败的图片
                //.crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(imageView);//加载
    }

    public static void loadLiveCover(Context context, ImageView imageView, String url) {
        Glide.with(context).
                load(url)//图片的url
                .centerCrop()//图片的显示方式。这里在是居中裁剪
//                .placeholder(R.drawable.drawable_default_img_bg_gray) //默认的占位图片
//                .error(R.drawable.drawable_default_img_bg_gray) //加载失败的图片
                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(imageView);//加载
    }

    /**
     * 加载文件类型头像
     *
     * @param context   上下文对象
     * @param imageView 容器
     * @param file      头像文件
     */
    public static void loadAvatar(Context context, ImageView imageView, File file) {
        /*Glide.with(context)
                .load(file)//图片的url
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(R.color.bg_gray) //默认的占位图片
                .error(R.color.bg_gray) //加载失败的图片
                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(imageView);//加载*/
    }


    /**
     * 去除centerCrop
     *
     * @param context
     * @param imageView
     * @param url
     * @param listener
     */
    public static void loadAvatar(Context context, ImageView imageView, String url, RequestListener listener) {
        Glide.with(context).
                load(url)//图片的url
//                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片
                .crossFade(1000)//图片的加载效果，这里是淡入淡出，时间为1000毫秒
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .listener(listener)
                .into(imageView);//加载
    }

    /**
     * 通过回调获取Bitmap
     *
     * @param context
     * @param url
     * @param target
     * @return
     */
    public static void getBitmap(Context context, String url, SimpleTarget<Bitmap> target) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .into(target);

    }

    /**
     * 加载图片到自定义ImageView上
     *
     * @param context
     * @param imageView
     * @param url
     */
    public static void loadToBitmap(Context context, final ImageView imageView, String url) {
       /* if (TextUtils.isEmpty(url)) {
            return;
        }
        Glide.with(context)
                .load(MyApi.BASE_URL + url)
                .asBitmap()
                .placeholder(R.color.bg_gray)
                .error(R.color.bg_gray)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        imageView.setImageBitmap(bitmap);
                    }
                });*/
    }


    /**
     * IM聊天时的图片加载
     *
     * @param imageView
     * @param url
     */
    public static void loadIMImage(ImageView imageView, String url) {
      /*  Glide.with(BaseApplication.getContext())
                .load(url)
                .fitCenter()//图片的显示方式。这里在是居中裁剪
                .placeholder(R.drawable.ic_downloading_default)
                .error(R.drawable.ic_default_image)
//                .override((int) DensityUtils.dipToPx(BaseApplication.getContext(), 130)
//                        , (int) DensityUtils.dipToPx(BaseApplication.getContext(), 130))
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)//缓存策略
                .into(imageView);*/
    }

    /**
     * 把图片压缩成Base64传给后台
     *
     * @param path
     * @return
     */
    public static String Bitmap2StrByBase64(String path) {
        Bitmap bit = BitmapFactory.decodeFile(path);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 80, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * gride加载圆形图片
     *
     * @param context   上下文
     * @param imageView 要显示的控件
     * @param url       图片URl
     */
    public static void glideCircular(final Context context, final ImageView imageView, String url) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .centerCrop()//图片的显示方式。这里在是居中裁剪
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new BitmapImageViewTarget(imageView) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                        circularBitmapDrawable.setCircular(true);//设置成圆形图片显示
                        imageView.setImageDrawable(circularBitmapDrawable);
                    }
                });

    }

    /**
     * gride加载圆角图片
     *
     * @param context   上下文
     * @param imageView 要显示的控件
     * @param url       图片URL
     * @param radius    圆角大小
     */
    public static void glideRound(final Context context, final ImageView imageView, String url, final float radius) {
        Glide.with(context)
                .load(url)
                .asBitmap()
                .centerCrop()
                .placeholder(DEFAULT_IMAGE) //默认的占位图片
                .error(ERROR_IMAGE) //加载失败的图片
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new BitmapImageViewTarget(imageView) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                        circularBitmapDrawable.setCornerRadius(radius);//设置成圆角方形图片,圆角大小
                        imageView.setImageDrawable(circularBitmapDrawable);
                    }
                });
    }

    public static void loadFileAndSave(Context context,ImageView imageView,File file){
        Glide.with(context).
                load(file)//图片的url
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                .into(new  BitmapImageViewTarget(imageView) {
                    public void setResource(Bitmap resource) {
                        imageView.setImageBitmap(resource);
                        FileOutputStream fos = null;
                        try {
                            fos = new FileOutputStream(file.getAbsolutePath()+file.getName());
                            resource.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                            fos.flush();
                            fos.close();
                        } catch (Exception e) {
                            Log.e("Tag","e="+e.getMessage());
                            e.printStackTrace();
                        }

                    }
                });
    }

    static class GlideCircleTransform extends BitmapTransformation {

        private Paint mBorderPaint;
        private float mBorderWidth;

        public GlideCircleTransform(Context context) {
            super(context);
        }

        public GlideCircleTransform(Context context, int borderWidth, int borderColor) {
            super(context);
            mBorderWidth = Resources.getSystem().getDisplayMetrics().density * borderWidth;

            mBorderPaint = new Paint();
            mBorderPaint.setDither(true);
            mBorderPaint.setAntiAlias(true);
            mBorderPaint.setColor(borderColor);
            mBorderPaint.setStyle(Paint.Style.STROKE);
            mBorderPaint.setStrokeWidth(mBorderWidth);
        }


        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return circleCrop(pool, toTransform);
        }

        private Bitmap circleCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            int size = (int) (Math.min(source.getWidth(), source.getHeight()) - (mBorderWidth / 2));
            int x = (source.getWidth() - size) / 2;
            int y = (source.getHeight() - size) / 2;
            // TODO this could be acquired from the pool too
            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
            Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
            }
            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            float r = size / 2f;
            canvas.drawCircle(r, r, r, paint);
            if (mBorderPaint != null) {
                float borderRadius = r - mBorderWidth / 2;
                canvas.drawCircle(r, r, borderRadius, mBorderPaint);
            }
            return result;
        }

        @Override
        public String getId() {
            return getClass().getName();
        }


    }
}
